package com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.impl;

import com.alibaba.citrus.cr.mn.order.center.facade.adapter.ItemQueryAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.ItemSpecQueryAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ItemGroupAbilityRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ItemSearchAbilityRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ItemUnitAbilityRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.*;
import com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.OrderBizAssemble;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crplatformenhance.api.scitemquery.service.ScItemQueryService;
import com.epoch.app.crplatformenhance.model.dto.ScItemSDO;
import com.epoch.app.mnordercenter.orderbaserequest.OrderBizUpdateRequest;
import com.epoch.app.mnordercenter.orderbaserequest.OrderLineAtomUpdateRequest;
import com.epoch.app.mnordercenter.service.MnOrderCenterService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toMap;

/**
 * @author zhangxiaorui
 * @ClassName OrderBizAssembleOfMember
 * @description: TODO
 * @date 2023/05/17 09:49
 * @version: 1.0
 */
@Service
@Order(2)
public class OrderUpdateBizAssembleOfItemCenter implements OrderBizAssemble<OrderBizUpdateRequest> {

    private static final Log log = Log.getLogger(OrderUpdateBizAssembleOfItemCenter.class);

    @Resource
    private ScItemQueryService scItemQueryService;

    @Resource
    private MnOrderCenterService mnOrderCenterService;

    @Resource
    private ItemQueryAdapter itemQueryAdapter;

    @Resource
    private ItemSpecQueryAdapter itemSpecQueryAdapter;

    @Override
    public Map<String, Object> query(OrderBizUpdateRequest orderBizUpdateRequest) {
       return query(Arrays.asList(orderBizUpdateRequest));
    }

    @Override
    public Map<String, Object> query(List<OrderBizUpdateRequest> orderBizUpdateRequest) {
        try {
            Map<String, Object> result = Maps.newHashMap();
            // 物料
            Map<String, ItemSearchAbilityDTO> scItemInfoMap = queryScItemMap(orderBizUpdateRequest);
            if(scItemInfoMap.isEmpty()){
                //物料如果是空的，说明子单都是remark更新，不涉及物料变更，后续就不用查了
                return result;
            }
            // 产品组
            Map<String, ItemGroupAbilityDTO> scItemGroupListQueryMap = queryScItemGroupMap(orderBizUpdateRequest);
            // 销售单位、库存单位
            Map<String, ItemUnitAbilityDTO> scItemUnitListQueryMap = queryScItemUnitMap(orderBizUpdateRequest);
            // 箱柜关系
            Map<String, Integer> productConvertRelationMap = productConvertRelation(orderBizUpdateRequest);
            result.put(SC_ITEM_GROUP, scItemGroupListQueryMap);
            result.put(SC_ITEM_UNIT, scItemUnitListQueryMap);
            result.put(SC_ITEM_INFO, scItemInfoMap);
            result.put(SC_ITEM_CONVERT_RELATION, productConvertRelationMap);
            log.info("修改订单商业能力商品中心数据组装结果 result={}", JSONObject.toJSONString(result));
            return result;
        } catch (Exception e) {
            log.error("修改订单商业能力商品中心数据组装失败", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result<String> assemble(Map<String, Object> queryResponseMap, OrderBizUpdateRequest orderBizUpdateRequest) {
        log.info("OrderUpdateBizAssembleOfItemCenter#assemble queryResponseMap:{}; orderBizUpdateRequest:{}", JSONObject.toJSONString(queryResponseMap), JSONObject.toJSONString(orderBizUpdateRequest));
        // 产品组
        Map<String, ItemGroupAbilityDTO> scItemGroupMap = getBizInfoMap(queryResponseMap, SC_ITEM_GROUP, ItemGroupAbilityDTO.class);
        // 销售单位、库存单位
        Map<String, ItemUnitAbilityDTO> scItemUnitMap = getBizInfoMap(queryResponseMap, SC_ITEM_UNIT, ItemUnitAbilityDTO.class);
        // 物料
        Map<String, ItemSearchAbilityDTO> scItemInfoMap = getBizInfoMap(queryResponseMap, SC_ITEM_INFO, ItemSearchAbilityDTO.class);
        // 箱柜关系
        Map<String, Integer> productConvertRelationMap = getBizInfoMap(queryResponseMap, SC_ITEM_CONVERT_RELATION, Integer.class);
        log.info("OrderUpdateBizAssembleOfItemCenter#assemble scItemUnitMap:{}; scItemInfoMap:{}; productConvertRelationMap:{}",
                JSONObject.toJSONString(scItemUnitMap), JSONObject.toJSONString(scItemInfoMap), JSONObject.toJSONString(productConvertRelationMap));
        for (OrderLineAtomUpdateRequest updateRequest : orderBizUpdateRequest.getOrderDetails()) {
            if(StringUtils.isNotBlank(updateRequest.getSalesUnitCode())) {
                // 销售单位
                ItemUnitAbilityDTO scItemUnit = scItemUnitMap.get(updateRequest.getSalesUnitCode());
                if (Objects.isNull(scItemUnit)) {
                    return Result.fail(orderBizUpdateRequest.getSalesOrderNo(), "OC-01-001-01-16-052", "销售单位不存在");
                }
                updateRequest.setSalesUnitName(scItemUnit.getUnitName());
            }
            // 物料信息
            ItemSearchAbilityDTO scItem=new ItemSearchAbilityDTO();
            if(StringUtils.isNotBlank(updateRequest.getProductCode())) {
                 scItem = scItemInfoMap.get(updateRequest.getProductCode());
                if (Objects.isNull(scItem)) {
                    return Result.fail(orderBizUpdateRequest.getSalesOrderNo(), "OC-01-001-01-16-034", "销售组织编码/名称不存在");
                }
                updateRequest.setInnerProductCode(scItem.getProductCode());
                updateRequest.setInnerProductName(scItem.getTitle());
                updateRequest.setProductBarCode(scItem.getBarCode());
                updateRequest.setProductName(scItem.getTitle());
                updateRequest.setStockUnitName(scItem.getUnit());
                updateRequest.setStockUnitCode(scItem.getUnitCode());
            }
            // 库存转换数量计算
            if (StringUtils.isNotBlank(updateRequest.getProductCode()) && StringUtils.isNotBlank(updateRequest.getSalesUnitCode())) {
//                Integer productConvert = productConvertRelationMap.get(scItem.getOuterId()+"_"+scItem.getUnitCode());
                Integer productConvert = productConvertRelationMap.get(scItem.getOuterId() + "_" + updateRequest.getSalesUnitCode());
                log.info("OrderUpdateBizAssembleOfItemCenter_assmble:"+productConvert+"=="+scItem.getOuterId()+"=="+updateRequest.getSalesUnitCode());
                if (Objects.isNull(productConvert)) {
                    return Result.fail(orderBizUpdateRequest.getSalesOrderNo(), "OC-04-001-01-16-010","销售单位编码不存在");
                }
                String stockConversionNum = new BigDecimal(String.valueOf(productConvert)).toPlainString();
                if (StringUtils.isNotBlank(stockConversionNum) && StringUtils.isNotBlank(updateRequest.getProductQuantity())) {
                    updateRequest.setUnitConversionRelationship(stockConversionNum);
                    BigDecimal quantity = new BigDecimal(updateRequest.getProductQuantity());
                    BigDecimal convert = new BigDecimal(stockConversionNum);
                    BigDecimal conversionNum = quantity.divide(convert, 3, RoundingMode.HALF_UP);
                    updateRequest.setStockConversionNum(conversionNum.toPlainString());
                }
            }

        }
        return Result.success(null);
    }

//    private String calculateInventoryConvertNum(ItemSearchAbilityDTO scItem, ItemUnitAbilityDTO scItemSalesUnit,
//                                                Map<String, Integer> productConvertRelationMap) {
//
//        Integer productConvert = productConvertRelationMap.get(scItem.getProductCode()+"_"+scItem.getUnitCode());
//        if (Objects.isNull(productConvert)) {
//            throw new FunctionException("OC-04-001-01-16-010");
//        }
//        return new BigDecimal(String.valueOf(productConvert)).toPlainString();
//    }

    private Map<String, ItemGroupAbilityDTO> queryScItemGroupMap(List<OrderBizUpdateRequest> exchangeOrderBizCreateRequests) {
        // 查询所有货品组数据
        ItemGroupAbilityRequest listRequest = new ItemGroupAbilityRequest();
        listRequest.setLimit(999);
        List<ItemGroupAbilityDTO> listResponse = itemQueryAdapter.queryScItemGroup(listRequest);
        return listResponse.stream().collect(Collectors.toMap(ItemGroupAbilityDTO::getProductGroupCode, p -> p, (v1, v2) -> v1));
    }

    private Map<String, ItemSearchAbilityDTO> queryScItemMap(List<OrderBizUpdateRequest> exchangeOrderBizCreateRequests) {
        List<String> scItemOutIds = Lists.newArrayList();
        for (OrderBizUpdateRequest exchangeOrderBizCreateRequest : exchangeOrderBizCreateRequests) {
            for (OrderLineAtomUpdateRequest updateRequest : exchangeOrderBizCreateRequest.getOrderDetails()) {
                scItemOutIds.add(updateRequest.getProductCode());
            }
        }
        if(CollectionUtils.isEmpty(scItemOutIds)) {
            return Maps.newHashMap();
        }
        ItemSearchAbilityRequest listRequest = new ItemSearchAbilityRequest();
        listRequest.setProductCodes(scItemOutIds);
        listRequest.setStatusList(Collections.singletonList(1));
        List<ItemSearchAbilityDTO> scItemInfoList = itemQueryAdapter.queryItem(listRequest);

        return Optional.ofNullable(scItemInfoList)
                .orElse(Lists.newArrayList())
                .stream().collect(Collectors.toMap(ItemSearchAbilityDTO::getOuterId, p -> p, (v1, v2) -> v1));
    }

    private List<ScItemSDO> parseScItemInfoList(Object listResponse) {
        JSONObject listResponseMap = JSONObject.parseObject((String) listResponse);
        JSONObject level1 = listResponseMap.getJSONObject("result");
        if (MapUtils.isEmpty(level1)) {
            return Lists.newArrayList();
        }
        JSONObject level2 = level1.getJSONObject("result");
        if (MapUtils.isEmpty(level2)) {
            return Lists.newArrayList();
        }
        JSONArray content = level2.getJSONArray("content");
        if (CollectionUtils.isEmpty(content)) {
            return Lists.newArrayList();
        }
        return JSONArray.parseArray(content.toJSONString(), ScItemSDO.class);
    }

    private Map<String, ItemUnitAbilityDTO> queryScItemUnitMap(List<OrderBizUpdateRequest> exchangeOrderBizCreateRequests) {
        // 查询所有单位库数据
        ItemUnitAbilityRequest listRequest = new ItemUnitAbilityRequest();
        listRequest.setLimit(999);
        List<ItemUnitAbilityDTO> listResponse = itemQueryAdapter.queryScItemUnitMap(listRequest);
        return listResponse.stream().collect(Collectors.toMap(ItemUnitAbilityDTO::getUnitCode, p -> p, (v1, v2) -> v1));
    }

    private Map<String, Integer> productConvertRelation(List<OrderBizUpdateRequest> exchangeOrderBizCreateRequests) {

        List<String> materialCodeList = Lists.newArrayList();
        for (OrderBizUpdateRequest exchangeOrderBizCreateRequest : exchangeOrderBizCreateRequests) {
            for (OrderLineAtomUpdateRequest updateRequest : exchangeOrderBizCreateRequest.getOrderDetails()) {
                if (StringUtils.isNotBlank(updateRequest.getProductCode())) {
                    materialCodeList.add(updateRequest.getProductCode());
                }
            }
        }

        if (CollectionUtils.isEmpty(materialCodeList)) {
            return Maps.newHashMap();
        }
        log.info("OrderUpdateBizAssembleOfItemCenter_productConvertRelation_request={}", JSONObject.toJSONString(materialCodeList));

        List<SpecConvertCoefficientDTO> listResult =
                itemSpecQueryAdapter.queryConvertCoefficientByMaterialCodeList(materialCodeList);
        log.info("OrderUpdateBizAssembleOfItemCenter_productConvertRelation_result={}", JSONObject.toJSONString(listResult));
        if (CollectionUtils.isEmpty(listResult)) {
            return Maps.newHashMap();
        }
        //借鉴自com.alibaba.citrus.cr.mn.order.center.facade.forecastorder.service.impl.ForecastOrderBizWriteServiceImpl  624行 unitConvertMap
        Map<String, Integer> unitConvertMap = new HashMap<>();
        Map<String, List<SpecConvertCoefficientDetailDTO>> collect = listResult.stream().collect(Collectors.toMap(x->x.getMaterialCode(), SpecConvertCoefficientDTO::getConvertCoefficientList, (v1, v2) -> v1));
        for (Map.Entry<String, List<SpecConvertCoefficientDetailDTO>> entry : collect.entrySet()) {
            String productCode = entry.getKey();
            unitConvertMap.putAll(entry.getValue().stream().collect(toMap(o->productCode + "_" +o.getUnitCode(),
                    SpecConvertCoefficientDetailDTO::getConvertCoefficient, (v1, v2) -> v1)));
        }
        return unitConvertMap;
    }
}
